# 作者 :南雨
# 时间 : 2022/6/27 22:38
from dzj.trec_qa.trec_constant import Trec_constant
# import trec_w2vec as w2v
import dzj.trec_qa.trec_w2vec as w2v
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score, recall_score, f1_score
from tensorflow.keras.preprocessing.sequence import pad_sequences
import numpy as np
import tensorflow as tf
from dzj.trec_qa.trec_model import train
from dzj.trec_qa.trec_w2vec import get_train_test_val


def text_to_sequence(texts):
    """
    把句子转换为模型输入的类型
    :param texts:
    :return:
    """
    text_processor = w2v.get_tokenizer()[0]
    text_num = text_processor.texts_to_sequences([texts])
    res_text = pad_sequences(text_num, maxlen=Trec_constant.max_len, padding='post', truncating='post')
    return res_text


def predict(text):
    """
    对句子做预测
    :param text: 输入的句子
    :return:
    """
    train_X, test_X, val_X, train_y, test_y, val_y, embeddings_matrix = get_train_test_val()
    # model = train(train_X, train_y, val_X, val_y, embeddings_matrix)
    model = train(train_X, train_y, val_X, val_y, embeddings_matrix)
    # model = tf.keras.models.load_model('../dzj/mymodel/trec.h5', compile=False)
    # model.compile(tf.optimizers.Adam(learning_rate=0.001),
    #               loss='categorical_crossentropy',
    #               metrics=['accuracy'])
    # y_pred = model.predict(test_X)
    # y_pred = np.argmax(y_pred, axis=1)
    # y_true = np.argmax(test_y, axis=1)
    # model.evaluate(test_X, test_y, batch_size=10)
    # model.save("../mymodel/trec.h5")
    y_pred = model.predict(test_X)
    y_pred = np.argmax(y_pred, axis=1)
    y_true = np.argmax(test_y, axis=1)

    precision = precision_score(y_true, y_pred, average='weighted')
    recall = recall_score(y_true, y_pred, average='weighted')
    f1 = f1_score(y_true, y_pred, average='weighted')

    text_label = model.predict(text_to_sequence(text))
    text_label = np.argmax(text_label, axis=1)[0]

    result = Trec_constant.labels[text_label]

    return result, '%.3f' % precision, '%.3f' % recall, '%.3f' % f1

#
# text = "What is autism ?"
# print(predict(text))
